package net.airtheva.uniqueTask5.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;

public class Utils {
	
	public static String MD5(String content) {
		
		try {
			
			byte[] hash;
			hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
			StringBuilder hex = new StringBuilder(hash.length * 2);
		    for (byte b : hash) {
		        if ((b & 0xFF) < 0x10) hex.append("0");
		        hex.append(Integer.toHexString(b & 0xFF));
		    }
		    return hex.toString();
		    
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
		
	}
	
	public static byte[] InputStreamToBytes(InputStream inputStream) {
		
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			int b;
			while((b = inputStream.read()) >= 0) {
				baos.write(b);
			}
			
			return baos.toByteArray();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	
	public static void WriteFile(File file, byte[] contents) {
		
		try {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(contents);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static String WrapNetworkImageUri(Context context, String uri) {
		
		try {
			String path = context.getCacheDir().getCanonicalPath() + "/" + MD5(uri);
			String newUri = "file://" + path;
			File file = new File(path);
			
			URL url = new URL(uri);
			HttpURLConnection huc = (HttpURLConnection) url.openConnection();
			huc.setDoInput(true);
			huc.connect();
			Utils.WriteFile(file, Utils.InputStreamToBytes(huc.getInputStream()));
			// To ensure others have access to the cache.
			file.setReadable(true, false);
			huc.disconnect();
			
			return newUri;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return uri;
		}
		
	}

}
